<template>
	<view>
		<view v-if="!showNoDataErr">
			<view style="margin-bottom: 30upx;">
				<image style="width: 100%;" :src="banner.screenshot" mode="widthFix" @click="bindPreview()"></image>
			</view>
			<view class='article'>
				<view class="author-info" v-if="(banner.avatar && banner.avatar != '') || (banner.author && banner.author != '') || (banner.bio && banner.bio != '')">
					<image @click="goUCenter(banner)" v-if="(banner.avatar && banner.avatar != '')" class="avatar" :src="banner.avatar"></image>
					<text @click="goUCenter(banner)" v-if="(banner.author && banner.author != '')" class="author-name">{{banner.author}}</text>
					<text style="float: right;text-align: right;margin-right: 20upx;" v-if="(banner.bio && banner.bio != '')" class="author-mark">发表于：{{banner.bio}}</text>
				</view>
				
				<view class="author-info">
					<text class="author-mark" style="font-size: 15px;">分类 : {{banner.type}}</text>
					<text class="author-mark" style="float: right;text-align: right;margin-right: 20upx;">{{banner.readCount}}人查看 - {{banner.goodCount}}人点赞</text>
				</view>
				
				<view class="articleContent">
					<!--  #ifndef MP-WEIXIN-->
					<div class="figure" v-for="(url, index) in videoUrls" :key="index" :id="index">
						<video id="myVideo" :src="url" controls style="width: 100%;"></video>
					</div>
					<!-- #endif -->
					<!-- <u-parse :content="banner.content || '加载中,请稍后...'" @preview="preview" @navigate="navigate" /> -->
					<!-- <rich-text :nodes="banner.content || '加载中,请稍后...'"></rich-text> -->
					<!--#ifndef APP-PLUS-->
					<parser :html="banner.content" @parser="parser" @ready="ready" @imgtap="imgtap" @linkpress="linkpress" @error="error"
					 show-with-animation lazy-load>加载中...</parser>
					<!--#endif-->
					<!--#ifdef APP-PLUS-->
					<parser :html="banner.content" @parser="parser" @ready="ready" @imgtap="imgtap" @linkpress="linkpress" @error="error"
					 show-with-animation lazy-load :autocopy="false">加载中...</parser>
					<!--#endif-->
				</view>
			</view>
		</view>
		
		<view class="s-page" v-if="showNoDataErr">
			<view class="is-100vh is-flex is-column is-justify-center is-align-center ">
				<image src="../../static/error/no.png" style="width: 50%;margin-top: -110px" mode="widthFix"></image>
				<view class="has-title-color is-size-16 has-mgt-30">亲，没有数据</view>
				<view class="s-btn has-mgt-20">
					<view @click="goHome()" class="is-btn has-bg-red has-btn-radius ">返回首页</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	const FAIL_CONTENT = '<p>获取信息失败</p>';
	
	import service from '../../common/service.js';
	
	import parser from "@/components/jyf-Parser/index"
		
	let utils = require("@/common/util.js")
	
	export default {
		data() {
			return {
				banner: {},
				horizontal: 'right',
				vertical: 'bottom',
				direction: 'vertical',
				showNoDataErr: false,
				collectionStatus: false,
				userinfo:{},
				token: null,
				pattern: {
					color: '#7A7E83',
					backgroundColor: '#fff',
					selectedColor: '#007AFF',
					buttonColor:"#007AFF"
				},
				imgUrls:[],
				videoUrls:[]
			}
		},
		onShareAppMessage() {
			return {
				title: this.banner.title,
				path: '/pages/article/detail?query=' + JSON.stringify(this.banner)
			}
		},
		onLoad(event) {
			if(!event.query){
				this.showNoDataErr = true;
				return;
			}
			// 目前在某些平台参数会被主动 decode，暂时这样处理。
			try {
				this.banner = JSON.parse(decodeURIComponent(event.query));
			} catch (error) {
				this.banner = JSON.parse(event.query);
			}
			this.init();
			this.getDetail();
			uni.setNavigationBarTitle({
				title: this.banner.title
			});
		},
		onNavigationBarButtonTap() {
			var that = this;
			if (this.providerList.length === 0) {
				uni.showModal({
					title: '当前环境无分享渠道!',
					showCancel: false
				});
				return;
			}
			let itemList = this.providerList.map(function(value) {
				return value.name;
			})
			itemList.push("一键下载所有图片");
			console.log(JSON.stringify(that.imgUrls));
			uni.showActionSheet({
				itemList: itemList,
				success: (res) => {
					console.log(res.tapIndex);
					switch (res.tapIndex){
						case 0:
							//分享
							uni.share({
								provider: this.providerList[res.tapIndex].id,
								scene: this.providerList[res.tapIndex].type && this.providerList[res.tapIndex].type === 'WXSenceTimeline' ?
									'WXSenceTimeline' : "WXSceneSession",
								type: 2,
								title: '【涨知识】' + that.banner.author,
								summary: that.banner.title,
								imageUrl: that.banner.screenshot,
								href: "https://m.bukaa.cn/#/pages/article/detail?query=" + encodeURIComponent(JSON.stringify({"id":that.banner.id})),
								success: (res) => {
									console.log("success:" + JSON.stringify(res));
								},
								fail: (e) => {
								}
							});
							break;
						case 1:
							//下载图片	
							if(that.imgUrls && that.imgUrls.length >0){
								for (let idx in that.imgUrls) {
									service.createDownload(that.imgUrls[idx]);
								}
							}
							break;
						default:
							break;
					}
				}
			})
		},
		methods: {
			getDetail() {
				var that = this;
				uni.request({
					url: 'https://bukaa.cn/api-cms/article/detail/' + this.banner.id,
					success: (res) => {
						if (res.statusCode == 200 && res.data.status == 'ok') {
							var detail = res.data.data.detail;
							if(!res.data.data || !res.data.data.detail){
								that.showNoDataErr = true;
								return;
							}
							var content = res.data.data.detail.beforeContent;
 							content = content.replace(/\<img/gi, '<img style="width:100%;height:auto"');
							content = content.replace(/(<!--.*?-->)/g, '')
							
							that.getVideoUrls(content);
							var screenshot = res.data.data.pic;
							screenshot = screenshot.replace('260w_195h','780w_585h');
							that.banner = {
								id:res.data.data.id,
								title: res.data.data.title,
								content: content,
								author: res.data.data.author,
								avatar: res.data.data.authorAvatar || 'http://io.bukaa.cn/touxiang-girl.png',
								bio: utils.getDateDiff(utils.formatTime(new Date(res.data.data.createTime))),
								screenshot: screenshot,
								readCount: res.data.data.readCount,
								goodCount: res.data.data.goodCount,
								type: res.data.data.type,
								authorId: res.data.data.authorId
							};
							that.getImgUrls(content);
							//that.getInfo();
						} else {
							that.showNoDataErr = true;
							return;
						}
					}
				});
			},
			bindPreview() {
				uni.previewImage({
					urls: this.imgUrls
				});
			},
			goUCenter(detail){
				uni.navigateTo({
					url: '/pages/article/user?query=' + encodeURIComponent(JSON.stringify(detail))
				});
			},
			getVideoUrls(str){
				var that = this;
				// 匹配图片（g表示匹配所有结果i表示区分大小写）
				let hrefReg = /http:\/\/.*?(?:.mp4|.mp4)/i
				
				let arr = str.match(hrefReg)
				if(!arr)
					return;
				console.log('所有已成功匹配图片的数组：' + arr)
				for (let i = 0; i < arr.length; i++) {
				  that.videoUrls.push(arr[0]);
				}
				console.log(JSON.stringify(that.videoUrls));
			},
			getImgUrls(str){
				var that = this;
				// 匹配图片（g表示匹配所有结果i表示区分大小写）
				let imgReg = /<img.*?(?:>|\/>)/gi
				// 匹配src属性
				let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
				let arr = str.match(imgReg)
				if(!arr)
					return;
				for (let i = 0; i < arr.length; i++) {
				  let srcs = arr[i].match(srcReg)
				  // 获取图片地址
				  if (srcs && srcs[1]) {
					str = str.replace(arr[i], srcs[1])
					that.imgUrls.push(srcs[1]);
				  }
				}
			},
			init() {
				//用户信息
				//this.token =  service.getToken();
				uni.getProvider({
					service: 'share',
					success: (e) => {
						console.log(JSON.stringify(e.provider));
						let data = []
						for (let i = 0; i < e.provider.length; i++) {
							switch (e.provider[i]) {
								case 'weixin':
									data.push({
										name: '分享到微信好友',
										id: 'weixin',
										sort:0
									})
									data.push({
										name: '分享到微信朋友圈',
										id: 'weixin',
										type:'WXSenceTimeline',
										sort:1
									})
									break;
								case 'sinaweibo':
									data.push({
										name: '分享到新浪微博',
										id: 'sinaweibo',
										sort:2
									})
									break;
								case 'qq':
									data.push({
										name: '分享到QQ',
										id: 'qq',
										sort:3
									})
									break;
								default:
									break;
							}
						} 
						this.providerList = data.sort((x,y) => {
							return x.sort - y.sort
						});
					},
					fail: (e) => {
						console.log('获取分享通道失败', e);
					}
				});
			},
			goHome(e){
				uni.switchTab({
					url: '/pages/list/list'
				});
			},
			preview(src, e) {
			  // do something
			},
			navigate(href, e) {
			  // do something
			},
			parser(res) {
				console.log("parse finish", res);
			},
			ready(res) {
				console.log("ready", res);
			},
			imgtap(res) {
				console.log("imgtap", res);
			},
			linkpress(res) {
				console.log("linkpress", res);
				// #ifdef APP-PLUS
				if (/http/.test(res.href))
					uni.navigateTo({
						url: '../web/web?src=' + res.href
					})
				// #endif
			},
			error(res) {
				console.error(res);
			}
		},
		components: {
			// uParse
			parser
		}
	}
</script>

<style>
	page {
	  background: #fafafa;
	}
	.header-cover {
	  position: relative;
	  height: 500rpx;
	  overflow: hidden;
	}

	.header-cover image {
	  width: 100%;
	}

	.header-cover .mask {
	  position: absolute;
	  top: 0;
	  left: 0;
	  bottom: 0;
	  width: 100%;
	  background: rgba(0, 0, 0, 0.3);
	}

	.header-cover .desc {
	  position: absolute;
	  left: 0;
	  bottom: 0;
	  padding: 0 20rpx 60rpx 20rpx;
	  font-size: 40rpx;
	  color: #fff;
	  z-index: 10;
	}

	.header-cover .cover-source {
	  position: absolute;
	  right: 20rpx;
	  bottom: 20rpx;
	  font-size: 30rpx;
	  color: #fff;
	}

	.black-desc {
	  padding: 50rpx;
	  font-weight: bold;
	}

	/*article*/

	.article {
	  background: #fff;
	  padding: 15upx 15upx;
	}

	.article .title {
	  padding-bottom: 40rpx;
	  font-size: 40rpx;
	  font-weight: bold;
	}

	.article .author-info {
	  overflow: hidden;
	  height: 70upx;
	  line-height: 70upx;
	  font-size: 35rpx;
	  white-space: nowrap;
	  text-overflow: ellipsis;
	  margin-left: 10upx;
	}

	.article .author-info .avatar {
	  float: left;
	  width: 70upx;
	  height: 70upx;
	  border-radius: 50%;
	  line-height: 70upx;
	}

	.article .author-info .author-mark {
	  line-height: 70upx;
	  color: #6a6a6a;
	}

	.author-mark {
	  position: relative;
	  bottom: 0px;
	  padding: 0px;
	  margin: 0px;
	  font-size: 10px;
	  height: 60rpx;
	  overflow: hidden; /*自动隐藏文字*/
	  text-overflow: ellipsis; /*文字隐藏后添加省略号*/
	  white-space: nowrap; /*强制不换行*/
	  color: #69f;
	  width: 300rpx;
	}

	.article .author-info text {
	  display: block;
	  float: left;
	  padding-left: 10upx;
	  line-height: 70upx;
	}	
	
	.author-name{
		
	}
		
		
	a.listItemMetaTitle {
	  color: @heading-color;
	}
 

	article,aside,details,figcaption,figure,footer,header,main,menu,nav,section,summary {
	  display: block
	}

	audio,canvas,progress,video {
	  display: inline-block
	}

	audio:not([controls]) {
	  display: none;
	  height: 0
	}

	progress {
	  vertical-align: baseline
	}

	[hidden],template {
	  display: none
	}

</style>
